package com.smart;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Bean生命周期的各个步骤
 *
 * @author chenxingyu
 * @date 2019/8/26 20:12
 */
public class Car implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean, ApplicationContextAware {
    private String brand;
    private String color;
    private int maxSpeed;

    private BeanFactory beanFactory;
    private String beanName;

    private ApplicationContext applicationContext;

    public Car() {
        System.out.println("调用Car()构造函数");
    }

    public void setBrand(String brand) {
        System.out.println("调用car.setBrand() "+brand);
        this.brand = brand;
    }

    public void setColor(String color){
        System.out.println("调用car.setColor()"+color);
        this.color = color;
    }
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public String getBrand() {
        return brand;
    }

    public String getColor() {
        return color;
    }

    public void introduce() {
        System.out.println("brand:" + brand + ";color:" + color + ";maxSpeed:" + maxSpeed);
    }

    /**
     * BeanFactoryAware接口方法
     */
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("调用BeanFactoryAware.setBeanFactory()。");
        this.beanFactory = beanFactory;
    }

    public void setBeanName(String name) {
        System.out.println("调用BeanNameAware.setBeanName()。");
        this.beanName = name;
    }

    public void destroy() throws Exception {
        System.out.println("调用DisposableBean.destroy()。");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("调用InitializingBean.afterPropertiesSet()。");
    }

    public void myInit() {
        //通过<bean>的init-method属性指定初始化方法
        System.out.println("调用init-methods所指定的myInit(),将maxSpeed设置为240。");
        this.maxSpeed = 240;
    }

    public void myDestroy() {
        //通过<bean>的destroy-method属性指定销毁方法
        System.out.println("调用destroy-methods所指定的myDestroy()。");
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", color='" + color + '\'' +
                ", maxSpeed=" + maxSpeed +
                ", beanFactory=" + beanFactory +
                ", beanName='" + beanName + '\'' +
                ", applicationContext=" + applicationContext +
                '}';
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("调用ApplicationContext.setApplicationContext()。");
        this.applicationContext = applicationContext;
    }
}
